using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace KNCApp.Util
{
    public static class InvocationHelper
    {
        public static void Invoke(Delegate handler, params object[] arguments)
        {
            int requiredParameters = handler.Method.GetParameters().Length;
            // Check that the correct number of arguments have been supplied
            if (requiredParameters != arguments.Length)
            {
                throw new ArgumentException(string.Format(
                     "{0} arguments provided when {1} {2} required.",
                     arguments.Length, requiredParameters, 
                     ((requiredParameters == 1) ? "is" : "are")));
            }
            // Get a local copy of the invocation list in case it changes
            Delegate[] invocationList = handler.GetInvocationList();
            // Check that it's not null
            if (invocationList == null)
                return;
            // Loop through delegates and check for ISynchronizeInvoke
            foreach (Delegate singleCastDelegate in invocationList)
            {
                ISynchronizeInvoke synchronizeTarget = 
                    singleCastDelegate.Target as ISynchronizeInvoke;
                // Check to see if the interface was supported
                if (synchronizeTarget == null)
                {
                    // Invoke delegate normally
                    singleCastDelegate.DynamicInvoke(arguments);
                }
                else
                {
                    // Invoke through synchronization interface
                    synchronizeTarget.BeginInvoke(
                        singleCastDelegate, arguments);
                }
            }
        }
    }
}

